package com.asion.gankapp.view.fragments;


import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.asion.gankapp.R;
import com.asion.gankapp.adapters.BaseRecyclerAdapter;
import com.asion.gankapp.applacation.MyApp;
import com.asion.gankapp.entrys.BaseEntry;
import com.asion.gankapp.entrys.BaseMeituEntry;
import com.asion.gankapp.presenter.AlltypePresenter;
import com.asion.gankapp.presenter.BasePresenter;
import com.asion.gankapp.presenter.MeituPresenter;
import com.asion.gankapp.servers.Api;
import com.asion.gankapp.utils.MyDerocation;
import com.asion.gankapp.utils.MyDownLoadTask;
import com.asion.gankapp.utils.downbutton.CircularProgressButton;
import com.asion.gankapp.utils.refresh.CircleRefreshLayout;
import com.asion.gankapp.view.BaseView;
import com.asion.gankapp.view.activities.WebActivity;


/**
 * A simple {@link Fragment} subclass.
 */
public class BaseRecyclerFragment extends Fragment implements BaseView<BasePresenter>,CircleRefreshLayout.OnCircleRefreshListener {

    private FrameLayout baserecyclercontainer;
    private RecyclerView baserecycler;
    private AlltypePresenter basePresenter;
    private MeituPresenter meituPresenter;
    private String title;
    private int type;
    private BaseRecyclerAdapter baseRecyclerAdapter;
    private CircleRefreshLayout refresh;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 100:
                    refresh.finishRefreshing();
                    break;
            }
        }
    };
    private int pos;
    private Dialog dialog;
    private boolean isLoading;
    private int page=1;

    public static BaseRecyclerFragment newInstance(String title, int type,int pos) {
        Bundle bundle = new Bundle();
        bundle.putString("title", title);
        bundle.putInt("type", type);
        bundle.putInt("pos",pos);
        BaseRecyclerFragment baseRecyclerFragment = new BaseRecyclerFragment();
        baseRecyclerFragment.setArguments(bundle);
        return baseRecyclerFragment;
    }

    @Override
    public void onResume() {
        super.onResume();
        if(type == BaseRecyclerAdapter.ALLTYPE){
            basePresenter.start(title, 1);
        }
        if(type == BaseRecyclerAdapter.MEITU){
            meituPresenter.start(pos,1);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_base_recycler, container, false);
        initView(view);
        Bundle arguments = getArguments();
        title = arguments.getString("title");
        type = arguments.getInt("type");
        pos = arguments.getInt("pos");
        baseRecyclerAdapter = new BaseRecyclerAdapter(MyApp.context);
        baserecycler.setItemAnimator(new DefaultItemAnimator());
        if (type == BaseRecyclerAdapter.ALLTYPE) {
            initAlltype();
        }else if(type == BaseRecyclerAdapter.MEITU){
            initMeitu();
        }
        baserecycler.setAdapter(baseRecyclerAdapter);
        return view;
    }

    private void initMeitu() {
        meituPresenter = new MeituPresenter(this);
        baserecyclercontainer.setBackgroundResource(R.color.colorSecondText);
        baserecycler.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
        baseRecyclerAdapter.setType(2);
        baseRecyclerAdapter.setOnImageClickListener((view, position, url) -> {
            show(((ImageView) view),url);
        });
        baseRecyclerAdapter.setOnIntenetClickListenr((view, id, title1) -> {
            toWeb(Api.web+id,title1,null);
        });
        baserecycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                StaggeredGridLayoutManager layoutManager = (StaggeredGridLayoutManager) recyclerView.getLayoutManager();
                int itemCount = layoutManager.getItemCount();
                int[] lastVisibleItemPositions = layoutManager.findLastVisibleItemPositions(null);
                if (!isLoading && itemCount < (lastVisibleItemPositions[1] +8)) {
                    meituPresenter.start(pos,++page);
                    isLoading = true;
                }
            }
        });
    }

    private void initAlltype() {
        basePresenter = new AlltypePresenter(this);
        baserecycler.setLayoutManager(new LinearLayoutManager(MyApp.context));
        baserecycler.addItemDecoration(new MyDerocation(getContext(), LinearLayout.VERTICAL,1, Color.GRAY));
        baseRecyclerAdapter.setType(1);
        baseRecyclerAdapter.setOnItemClickListener((view, position, resultsBean, gank) -> {
            Bundle bundle = new Bundle();
            bundle.putSerializable("resultBean",resultsBean);
            toWeb(null,null,bundle);
        }
        );
        baserecycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int totalItemCount = layoutManager.getItemCount();
                int lastVisibleItem = layoutManager.findLastVisibleItemPosition();
                if (!isLoading && totalItemCount < (lastVisibleItem + 8)) {
                    basePresenter.start(title,++page);
                    isLoading = true;
                }
            }
        });
    }

    private void toWeb(String url, String desc,Bundle bundle1) {
        Intent intent = new Intent(getActivity(), WebActivity.class);
        intent.putExtra("desc", desc);
        intent.putExtra("url", url);
        intent.putExtra("bundle",bundle1);
        Bundle bundle = ActivityOptionsCompat.makeCustomAnimation(getContext(), R.anim.in, R.anim.out).toBundle();
        ActivityCompat.startActivity(getActivity(), intent, bundle);
    }

    private void initView(View view) {
        baserecyclercontainer = (FrameLayout) view.findViewById(R.id.base_recycler_container);
        baserecycler = (RecyclerView) view.findViewById(R.id.base_recycler);
        refresh = ((CircleRefreshLayout) view.findViewById(R.id.refresh_layout));
        dialog = new Dialog(view.getContext(), R.style.Dialog);
        refresh.setOnRefreshListener(this);
    }

    @Override
    public void setPresenter(BasePresenter presenter) {
        if(type == BaseRecyclerAdapter.ALLTYPE){
            basePresenter = (AlltypePresenter) presenter;
        }
        if(type == BaseRecyclerAdapter.MEITU){
            meituPresenter = ((MeituPresenter) presenter);
        }
    }

    @Override
    public void showAllTypeSuccess(BaseEntry baseEntry) {
        if(type ==BaseRecyclerAdapter.ALLTYPE && baseEntry!=null){
            baseRecyclerAdapter.addAll(baseEntry.getResults());
            sendBroadCast();
        }
        isLoading = false;
    }

    private void sendBroadCast() {
        Intent intent = new Intent("baseFrag");
        intent.putExtra("over", "over");
        LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
    }

    @Override
    public void showAllTypeError(String s) {
        Snackbar.make(baserecyclercontainer, "数据请求失败", Snackbar.LENGTH_SHORT).show();
        isLoading = false;
    }

    @Override
    public void showMeituSuccess(BaseMeituEntry baseMeituEntry) {
        if(type == BaseRecyclerAdapter.MEITU && baseMeituEntry != null){
            baseRecyclerAdapter.addAll(baseMeituEntry.getTngou());
            sendBroadCast();
        }
        isLoading = false;
    }

    @Override
    public void showMeituError(String s) {
        Snackbar.make(baserecyclercontainer, "数据请求失败", Snackbar.LENGTH_SHORT).show();
        isLoading = false;
    }

    @Override
    public void completeRefresh() {
        Snackbar.make(baserecyclercontainer, "刷新完成", Snackbar.LENGTH_SHORT).show();
    }

    @Override
    public void refreshing() {
        baseRecyclerAdapter.removeAll();
        if(type == BaseRecyclerAdapter.ALLTYPE){
            basePresenter.start(title, 1);
        }
        if(type == BaseRecyclerAdapter.MEITU){
            meituPresenter.start(pos,1);
        }
        handler.sendEmptyMessageDelayed(100, 3000);
    }

    private void show(ImageView v, String url) {
        dialog.setContentView(R.layout.dialog_item);
        ImageView image = (ImageView) dialog.findViewById(R.id.dig_image);
        image.setImageDrawable(v.getDrawable());
        CircularProgressButton circularButton1 = (CircularProgressButton) dialog.findViewById(R.id.circularButton1);
        circularButton1.setIndeterminateProgressMode(true);
        circularButton1.setOnClickListener(a -> {
            new MyDownLoadTask(circularButton1).execute(url);
        });
        dialog.show();
    }
}
